package com.proactive.webapp.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.proactive.webapp.dao.ActivityDAO;
import com.proactive.webapp.dao.CardDAO;
import com.proactive.webapp.dao.CardTemplateDAO;
import com.proactive.webapp.dao.MemberDAO;
import com.proactive.webapp.dao.MenuDAO;
import com.proactive.webapp.entity.Activity;
import com.proactive.webapp.entity.Card;
import com.proactive.webapp.entity.CardTemplate;
import com.proactive.webapp.entity.Member;
import com.proactive.webapp.entity.Menu;
import com.proactive.webapp.util.AwsUtil;
import com.proactive.webapp.util.CompressImage;
import com.proactive.webapp.util.DateConversion;
import com.proactive.webapp.util.FileUtil;
import com.proactive.webapp.util.MenuUtil;
import com.proactive.webapp.util.PageCount;

@Controller
public class MemberCardController {
	ApplicationContext context =  new ClassPathXmlApplicationContext("spring-module.xml");
	@RequestMapping(value = "/addCardCont", method = RequestMethod.GET)
	public ModelAndView addCardCont(HttpServletRequest request, HttpSession session) {
		ModelAndView model = new ModelAndView();	

		//check login
		Member loginMember = (Member)session.getAttribute("loginMember");
		if(loginMember != null){
			
			//import DAO
			ActivityDAO activityDAO = (ActivityDAO) context.getBean("activityDAO");
			CardTemplateDAO cardTemplateDAO = (CardTemplateDAO) context.getBean("cardTemplateDAO");
			
			//get data from request
			//int activityID = request.getParameter("aid")==null?1:Integer.parseInt(request.getParameter("aid"));
			int cardTemplateID = request.getParameter("id")==null?1:Integer.parseInt(request.getParameter("id"));
			int activityID = 1;
			
			Activity activity = new Activity();
			activity.setId(activityID);
			activity.setStatus(1);
			activity = activityDAO.getByStatus(activity);
			
			CardTemplate cardTemplate = new CardTemplate();
			cardTemplate.setId(cardTemplateID);
			cardTemplate.setStatus(1);
			cardTemplate = cardTemplateDAO.getByStatus(cardTemplate);
	
			List<Menu> menuList = MenuUtil.getList(((MenuDAO)context.getBean("menuDAO")).getList(), 5);
			
			//set model
			model.addObject("activity", activity);
			model.addObject("cardTemplate", cardTemplate);
			model.addObject("menuList", menuList);
			
			model.setViewName("addCard");
		}
		else
			model.setViewName("redirect:/login");
		return model;
	}
	
	@RequestMapping(value = "/addCard", method = RequestMethod.POST)
	public ModelAndView addCourse(@ModelAttribute Card card, HttpSession session, HttpServletRequest request) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){
			String path = session.getServletContext().getRealPath("resources/image/activity/card/");
			DateConversion dateConversion = new DateConversion();
			Date now = new Date();
			card.setAccount(loginMember.getAccount());
			if(card.getImage().getSize() > 0){				
				//new AWS
				AwsUtil awsUtil = new AwsUtil();
		        awsUtil.setPropertyPath(request.getServletContext().getRealPath("../AwsCredentials.properties"));
		        awsUtil.getInstance();
				
				FileUtil fileUtil = new FileUtil(card.getImage().getOriginalFilename());
				String newFileName = dateConversion.ConversionYMDHMS2(now) +"_"+ loginMember.getMemberNO() + "." + fileUtil.getFileType();
				
				//rename and move
				File targetFile = new File(path, newFileName);
		        if(!targetFile.exists()){
		            targetFile.mkdirs();
		        }
		        try {
		        	card.getImage().transferTo(targetFile);
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
		        
		        //compress image
				if(!fileUtil.getFileType().equals("gif")){
		    		CompressImage compressImage = new CompressImage();
		        	compressImage.compress(path+"/", newFileName, 0, 0, false);
		        }				

				//upload file AWS
				try {		        	
					awsUtil.uploadFile("resources/image/activity/card/", targetFile);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		        //delete local file
		        targetFile.delete();	
		        card.setImagePath("resources/image/activity/card/"+newFileName);
			}
			
			card.setContent(StringEscapeUtils.escapeHtml(card.getContent()));

			card.setStatus(card.getStatus()==2?2:1);
			
			CardDAO cardDAO = (CardDAO)context.getBean("cardDAO");
			int cardID = cardDAO.insert(card);

			model.setViewName("redirect:/showCard?id="+cardID);
		}
		else
			model.setViewName("redirect:/login");
		return model;
 
	}	
	
	@RequestMapping(value = "/memberCard", method = RequestMethod.GET)
	public ModelAndView getMemberCardList(HttpServletRequest request, HttpSession session) {
		ModelAndView model = new ModelAndView();
		Member loginMember = (Member)session.getAttribute("loginMember");
		if (request.getParameter("id") != null) {
			MemberDAO memberDAO = (MemberDAO) context.getBean("memberDAO");
			CardDAO cardDAO = (CardDAO) context.getBean("cardDAO");
			Member member = new Member();			
			List<Card> cardList = new ArrayList<Card>();
			
			String memberNO = request.getParameter("id");
			int pageNow = request.getParameter("p")==null?1:Integer.parseInt(request.getParameter("p"));
			
			member.setMemberNO(memberNO);
			member = memberDAO.getByMemberNO(member);//用memberNO取得memberAccount
			if(member.getAccount()!=null){
				if(loginMember != null)
					member = memberDAO.getByLogin(member, loginMember.getAccount());//取得member資料
				int count = 0;
				if(member.isMyselfFlag())
					count = cardDAO.countTotalByWriter(member.getAccount());
				else
					count = cardDAO.countTotalByMember(member.getAccount());
				
				
				//set pager
				int pageSize = 9;
				String pageUrl = "memberCard";
				String pageEndUrl1 = "&id="+memberNO;
				PageCount pageCount = new PageCount(pageNow, pageSize, count, pageUrl, pageEndUrl1);
				pageCount.calculate();
				
				if(member.isMyselfFlag())
					cardList = cardDAO.getListByWriter(member.getAccount(), pageCount.getStart(), pageSize);
				else
					cardList = cardDAO.getListByMember(member.getAccount(), pageCount.getStart(), pageSize);
				
				
				List<Menu> menuList = MenuUtil.getList(((MenuDAO)context.getBean("menuDAO")).getList(), 0);
				
				//set model
				model.addObject("page", pageCount);
				model.addObject("member", member);
				model.addObject("cardList", cardList);
				model.addObject("menuList", menuList);
				model.setViewName(loginMember!=null?"memberCard1":"memberCard2");
				
			}
			else
				model.setViewName("redirect:/");
			
		} 
		else
			model.setViewName(loginMember!=null?"redirect:/memberCard?id="+loginMember.getMemberNO():"redirect:/login");

		
		return model;
	}
	
	@RequestMapping(value = "/actCard", method = RequestMethod.POST)
	public ModelAndView actCard(int id, String act, HttpSession session, HttpServletRequest request) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){//檢查登入
			CardDAO cardDAO = (CardDAO) context.getBean("cardDAO");
			Card card = new Card();
			card.setId(id);
			card = cardDAO.get(card);
			if(card.getAccount().equals(loginMember.getAccount())){//檢查是否為作者
				if(act.equals("delete")){
					String path = session.getServletContext().getRealPath("/");
					if(!card.getImagePath().equals("")){
						//new AWS
						AwsUtil awsUtil = new AwsUtil();
				        awsUtil.setPropertyPath(request.getServletContext().getRealPath("../AwsCredentials.properties"));
				        awsUtil.getInstance();
				        awsUtil.deleteFile(card.getImagePath());
					}
					cardDAO.delete(card);
				}
				else if(act.equals("show")){
					card.setStatus(1);
					cardDAO.updateStatus(card);
				}
				else if(act.equals("hide")){
					card.setStatus(2);
					cardDAO.updateStatus(card);
				}
				model.setViewName("redirect:"+request.getHeader("referer"));
			}
			else 
				model.setViewName("redirect:/memberCard");
		}
		else
			model.setViewName("redirect:/login");
		return model;
 
	}
	
	
	@RequestMapping(value = "/modiCardCont", method = RequestMethod.GET)
	public ModelAndView modiCardCont(HttpSession session, int id) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){
			CardDAO cardDAO = (CardDAO) context.getBean("cardDAO");
			Card card = new Card();
			card.setId(id);
			card = cardDAO.get(card);
			if(card.getAccount().equals(loginMember.getAccount())){
				model.setViewName("modiCard");
				
				List<Menu> menuList = MenuUtil.getList(((MenuDAO)context.getBean("menuDAO")).getList(), 5);
				model.addObject("menuList", menuList);
				model.addObject("card", card);
			}
			else
				model.setViewName("redirect:/card");
			
		}
		else
			model.setViewName("redirect:/login");
		return model;
	}
	
	@RequestMapping(value = "/modiCard", method = RequestMethod.POST)
	public ModelAndView modiCard(@ModelAttribute Card card, HttpSession session, HttpServletRequest request) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){
			CardDAO cardDAO = (CardDAO)context.getBean("cardDAO");
			Card oldCard = new Card();
			oldCard.setId(card.getId());
			oldCard = cardDAO.get(oldCard);
			if(oldCard.getAccount().equals(loginMember.getAccount())){
				String path = session.getServletContext().getRealPath("/");
				String path1 = session.getServletContext().getRealPath("resources/image/activity/card/");
				DateConversion dateConversion = new DateConversion();
				Date now = new Date();
				card.setAccount(loginMember.getAccount());
				if(card.getImage().getSize() > 0){
					//new AWS
					AwsUtil awsUtil = new AwsUtil();
			        awsUtil.setPropertyPath(request.getServletContext().getRealPath("../AwsCredentials.properties"));
			        awsUtil.getInstance();
					
					FileUtil fileUtil = new FileUtil(card.getImage().getOriginalFilename());
					String newFileName = dateConversion.ConversionYMDHMS2(now) +"_"+ loginMember.getMemberNO() + "." + fileUtil.getFileType();
					
					//rename and move
					File targetFile = new File(path1, newFileName);
			        if(!targetFile.exists()){
			            targetFile.mkdirs();
			        }
			        try {
			        	card.getImage().transferTo(targetFile);
			        } catch (Exception e) {
			            e.printStackTrace();
			        }
			        
			        //delete original file
			        if(!oldCard.getImagePath().equals("")){
			        	awsUtil.deleteFile(oldCard.getImagePath());
			        }
		        	
		        	//compress image
					if(!fileUtil.getFileType().equals("gif")){
			    		CompressImage compressImage = new CompressImage();
			        	compressImage.compress(path1+"/", newFileName, 0, 0, false);
			        }
					
					//upload file AWS
			        try {
						awsUtil.uploadFile("resources/image/activity/card/", targetFile);
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			        
			        //delete local file
			        targetFile.delete();	

		        	card.setImagePath("resources/image/activity/card/"+newFileName);
				}
				else
		        	card.setImagePath(oldCard.getImagePath());

				card.setStatus(card.getStatus()==2?2:1);
				cardDAO.update(card);
				
				
			}
			model.setViewName("redirect:/showCard?id="+card.getId());
			
		}
		else
			model.setViewName("redirect:/login");
		return model;
 
	}	
}
